package com.dqhl.community.wxpay;

import android.app.Activity;
import android.util.Log;

import com.dqhl.community.util.Config;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 微信支付
 */
public class WxPaymentUtils {

    //用户APP相关;
    private Activity activity;                              //调用支付的界面;
    private String orderId;                                 //订单号;<必传>
    private String appId;
    private String noncestr;
    private String packages;
    private String partnerid;
    private String prepayid;
    private String sign;
    private String timestamp;

    private String totalFee;                                //订单价格;<必传>(例子: 18.90)
    private String productInfo;                             //订单简介;<必传>
    private String notifyUrl = "";   //支付结果回调;
    //private String notifyUrl = "http://m.baopindd.com/servlet/WxPaymentNotify";   //支付结果回调;

    //微信支付相关;
    private PayReq req;
    //    private String prepayId;                        //预支付交易会话ID
    private IWXAPI msgApi;

    //微信支付返回的结果;
    public static int weChatPaymentCode = 100;

    /**
     * 创建微信支付对象
     *
     * @param activity 当前界面;
     * @param orderId  后台生成的订单号(不允许重复);
     *                 //     * @param totalFee    保留小数点后两位的数值;
     *                 //     * @param productInfo 支付商品的信息;
     *                 //     * @param notifyUrl   服务器的微信回调地址;
     */
    public WxPaymentUtils(Activity activity, String orderId) {
        weChatPaymentCode = 100;
        this.activity = activity;
        this.orderId = orderId;
        req = new PayReq();
        msgApi = WXAPIFactory.createWXAPI(activity, null);
        msgApi.registerApp(Constants.APP_ID);
        Dlog.e("GG获取微信支付信息" + orderId);
    }

    /**
     * 支付;
     */
    public void payment() {
        RequestParams params = new RequestParams(Config.Api.wxPay);
        params.addBodyParameter("order_id", orderId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG获取微信支付信息" + result);
                int msg = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                Dlog.e(msg + " GG " + data);
                if (msg == 2000) {
                    appId = JsonUtils.getInfo(data, "appid");
                    partnerid = JsonUtils.getInfo(data, "partnerid");
                    prepayid = JsonUtils.getInfo(data, "prepayid");
                    packages = JsonUtils.getInfo(data, "package");
                    noncestr = JsonUtils.getInfo(data, "noncestr");
                    timestamp = JsonUtils.getInfo(data, "timestamp");
                    sign = JsonUtils.getInfo(data, "sign");

                    Dlog.e("GG " + appId + "   " + partnerid + "   " + prepayid + "   " + packages + "   " + noncestr + "   " + timestamp + "   " + sign);
                    genPayReq();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });

    }

    /**
     * 生成微信支付参数;
     */
    private void genPayReq() {
        Dlog.e("GGgenPayReqgenPayReq");
        req.appId = appId;
        req.nonceStr = noncestr;
        req.partnerId = partnerid;
        req.prepayId = prepayid;
        req.packageValue = packages;
        req.timeStamp = timestamp;
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", appId));
        signParams.add(new BasicNameValuePair("noncestr", noncestr));
        signParams.add(new BasicNameValuePair("package", packages));
        signParams.add(new BasicNameValuePair("partnerid", partnerid));
        signParams.add(new BasicNameValuePair("prepayid", prepayid));
        signParams.add(new BasicNameValuePair("timestamp", timestamp));
//        signParams.add(new BasicNameValuePair("sign", sign));
        req.sign = genAppSign(signParams);

        //第三步调起微信支付;
        sendPayReq();
    }


    /**
     * 调起微信支付;
     */
    private void sendPayReq() {
        Dlog.e("GG sendPayReqsendPayReq");
        msgApi.registerApp(Constants.APP_ID);
        msgApi.sendReq(req);
        getPaymentResult();
    }

    /**
     * 生成App签名;
     */
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);

        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    /**
     * 返回微信支付结果;
     */
    public static boolean getPaymentResult() {
        boolean result;
        Log.i("GG", "成功成功成功成功成功成功成功    " + weChatPaymentCode);
        if (weChatPaymentCode == 0) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }
}
